//
// Created by Administrator on 2021/3/1.
//
#include "uni_test_ui.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

UIContext *ui_context_test;

static void DisplayTextToBuffer(char *text){
  sprintf(ui_context_test->text_displayer, text);
}

static void UnitTestMain(){
  FILE *case_file = fopen("test/cases.txt","r");
  if(case_file){
    char key;
    char output_result[MAX_CHAR + 1];
    while (fscanf(case_file, " %c,%s", &key, output_result) != EOF) {
      if (HandleInput(ui_context_test->context, key)) {
        if (strcmp(output_result, ui_context_test->text_displayer) == 0) {
          printf("Input: %c, Output: %s, OK\n", key, output_result);
        }else {
          printf("Input %c, Output: %s, Expect: %s, ERROR\n", key, ui_context_test->text_displayer, output_result);
          exit(-1);
        }
      }
    }

    fclose(case_file);
  }else {
    perror("open case file");
  }
}

static void InitConsoleTest(){
  char *const kOutputBuffer = malloc(MAX_CHAR + 1);

  ui_context_test = malloc(sizeof(UIContext));
  ui_context_test->text_displayer = kOutputBuffer;
  ui_context_test->context = CreateCalcContext();
  ui_context_test->context->display_text = DisplayTextToBuffer;
}

static void DestroyConsoleTest(){
  DestroyCalcContext(&ui_context_test->context);
  free(ui_context_test->text_displayer);
  free(ui_context_test);
  ui_context_test = NULL;
}

int RunUnitTest(int argc, char *argv[]){
  InitConsoleTest();

  UnitTestMain();

  DestroyConsoleTest();
}
